<?php
/**
 * @description : based function utils pool
 * @author      : stephen.mo <stephen.mo@hotmail.com>
 * @date        : Mar 24,2011
 */

class BasedUtils {

    /**
     * @method-name : chkIpRange().
     * @description : check the IP address is or not in range.
     * @parameter   : (string)$ip_range - IP's range 
     * @parameter   : (string)$ip_address - the ip address.
     * @return      : bool
     * @author      : stephen.mo <stephen.mo@hotmail.com>
     * @date        : Mar 24,2011
     */
    static public function chkIpRange($ip_range,$ip_address) {/*{{{*/
        if (empty($ip_range)) return TRUE;
        if (empty($ip_address)) return FALSE;
        if (!preg_match($ip_range,$ip_address)) return FALSE;
        return TRUE;

    }/*}}}*/

    
    /**
     * @method-name : getDomainByUrl().
     * @description : get url's domain name.
     * @parameter   : (string)$url - the url of need.
     * @return      : String
     * @author      : stephen.mo <stephen.mo@hotmail.com>
     * @date        : Mar 24,2011
     */
    static public function getDomainByUrl($url) {/*{{{*/
        if (empty($url)) return NULL;
        preg_match("/^(http:\/\/)?([^\/]+)/i", $url, $matches);
        $host = $matches[2];
        preg_match("/[^\.\/]+\.[^\.\/]+\.[^\.\/]+$/", $host, $matches);
        return $matches[0];

    }/*}}}*/

    
    /**
     * @method-name : readableRandomString() 
     * @description : length of random string (must be a multiple of 2).
     * @parameter   : (int)$length - length you will want.
     * @return      : string.
     * @author      : stephne.mo <stephen.mo@hotmail.com>
     * @date        : Mar 31,2011
     */
    static public function readableRandomString($length = 6) {/*{{{*/
        $conso = array("b","c","d","f","g","h","j","k","l","m","n","p","r","s","t","v","w","x","y","z");   
        $vocal = array("a","e","i","o","u");
        $password = "";   
        srand ((double)microtime()*1000000);   
        $max = $length/2;   
        for($i=1; $i<=$max; $i++) {   
            $password.=$conso[rand(0,19)];   
            $password.=$vocal[rand(0,4)];   
        }
        return $password;  
    }/*}}}*/

    /**
     * @method-name : generateRand().
     * @description : length of random string.
     * @parameter   : (int)$length - the len of you want.
     * @return      : string.
     * @author      : stephen.mo <stephen.mo@hotmail.com>
     * @date        : Mar 31,2011
     */
    static public function generateRand($length) {/*{{{*/
        $c= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";   
        srand((double)microtime()*1000000);
        $rand = NULL;
        for($i=0; $i<$length; $i++) {   
            $rand.= $c[rand()%strlen($c)];   
        }
        return $rand;  
    }/*}}}*/

    /**
     * @method-name : chkEmail(). 
     * @description : check a email address is or not valid.
     * @parameter   : (string)$email - email address.
     * @parameter   : (bool)$test_mx - Is or need test mx?
     * @return      : bool
     * @author      : stephen.mo <stephen.mo@hotmail.com>
     * @date        : Mar 31,2011
     */
    static public function chkEmail($email, $test_mx = false) {/*{{{*/
        if(eregi("^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email)) {
            if($test_mx) {   
               list($username, $domain) = split("@", $email);
               return getmxrr($domain, $mxrecords);
            }
            else {   
                return TRUE;
            }
        }
        return FALSE;  
    }/*}}}*/

    /**
     * @method-name : listFiles().
     * @description : list all files on the $dir.
     * @parameter   : (string)$dir - directory path. full path.
     * @parameter   : (bool)$output - ouput a HTML string or array.
     * @return      : mixed
     * @author      : stephen.mo <stephen.mo@hotmail.com>
     * @date        : Mar 31,2011
     */
    static public function listFiles($dir,$output=false) {/*{{{*/
        $result = array();
        if(is_dir($dir)) {   
            if($handle = opendir($dir)) {  
                
                while(($file = readdir($handle)) !== false) {   
                    if($file != "." && $file != ".." && $file != "Thumbs.db") {
                        if (is_file($dir."/".$file)) {
                            if ($output) 
                                echo '<a target="_blank" href="'.$dir.$file.'">'.$file.'a><br>'."\n";
                            else 
                                $result[] = $file;
                        }
                    }   
                }
                closedir($handle);
            } 
        }
        return $result;
    }/*}}}*/  

    /**
     * @method-name : destroyDir().
     * @description : destroy a dir and delete all files on the dir.
     * @parameter   : (string)$dir - a dir.
     * @parameter   : (bool)$virtual - whether a virtual directory.
     * @return      : bool
     * @author      : stephen.mo <stephen.mo@hotmail.com>
     * @date        : Mar 31,2011
     */
    static public function destroyDir($dir, $virtual = false) { /*{{{*/
        $ds = DIRECTORY_SEPARATOR; 
        $dir = $virtual ? realpath($dir) : $dir;   
        $dir = substr($dir, -1) == $ds ? substr($dir, 0, -1) : $dir;   
        if (is_dir($dir) && $handle = opendir($dir)) {  
            while ($file = readdir($handle)) {   
                if ($file == '.' || $file == '..') {  
                    continue;
                }   
                elseif (is_dir($dir.$ds.$file)) {   
                    destroyDir($dir.$ds.$file);  
                }   
                else {  
                    unlink($dir.$ds.$file);   
                }  
            }   
            @closedir($handle);  
            @rmdir($dir);   
            return true;   
        }   
        else {
            return false;
        } 
    }/*}}}*/


    /**
     * @method-name : getRealIpAddr().
     * @description : get the real ip address ,even if use angent.
     * @parameter   : NULL
     * @return      : string.
     * @author      : stephen.mo <stephen.mo@hotmail.com>
     * @date        : Mar 31,2011
     */
    static public function getRealIpAddr() {/*{{{*/
        if (!emptyempty($_SERVER['HTTP_CLIENT_IP'])) {   
            $ip=$_SERVER['HTTP_CLIENT_IP'];   
        }  
        elseif (!emptyempty($_SERVER['HTTP_X_FORWARDED_FOR'])) { //to check ip is pass from proxy   
            $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];   
        }   
        else  {   
            $ip=$_SERVER['REMOTE_ADDR'];   
        }

        return $ip;  
    }/*}}}*/

    /**
     * @method-name : forceDownload().
     * @description : force download a file by path.
     * @parameter   : (string)$file - full path & file name.
     * @return      : NULL;
     * @author      : stephen.mo <stephen.mo@hotmail.com>
     * @date        : Mar 31,2011
     */
    static public function forceDownload($file) {/*{{{*/   
        if ((isset($file))&&(file_exists($file))) {   
            header("Content-length: ".filesize($file));   
            header('Content-Type: application/octet-stream');   
            header('Content-Disposition: attachment; filename="' . $file . '"');   
            readfile("$file");   
        }   
        else {  
            echo "No file selected";  
        }  
    }/*}}}*/ 


    /**
     * @method-name : getCloud().
     * @description : get a cloud with tags.
     * @parameter   : (array)$data - source data.
     * @parameter   : (int)$minFontSize - min font size.
     * @parameter   : (int)$maxFontSize - max font size.
     * @return      : string.
     * @author      : stephen.mo <stephen.mo@hotmail.com>
     * @date        : Mar 31,2011
     */
    static public function getCloud( $data = array(), $minFontSize = 12, $maxFontSize = 30 ) {/*{{{*/
        $minminimumCount = min( array_values( $data ) );   
        $maxmaximumCount = max( array_values( $data ) );   
        $spread = $maximumCount - $minimumCount; $cloudHTML = '';   
        $cloudTags = array();   
        $spread == 0 && $spread = 1;   
        foreach( $data as $tag => $count ) {   
            $size = $minFontSize + ( $count - $minimumCount ) * ( $maxFontSize - $minFontSize ) / $spread;  
            $cloudTags[] = '<a style="font-size: ' . floor( $size ) . 'px'  
                         . '" href="#" title="\'' . $tag 
                         . '\' returned a count of ' . $count . '">'  
                         . htmlspecialchars( stripslashes( $tag ) ) . 'a>';  
        }   
        return join( "\n", $cloudTags ) . "\n";  
    }/*}}}*/


    /**
     * @method-name : myTruncate().
     * @description : substr a string or world. eg:$short_string=myTruncate($long_string, 100, ' ');
     * @parameter   : (string)$string.
     * @parameter   : (int)$limit.
     * @parameter   : (string)$break.
     * @parameter   : (string)$pad.
     * @return      : string
     * @author      : stephen.mo <stephen.mo@hotmail.com>
     * @date        : Mar 31,2011
     */
    static public function myTruncate($string, $limit, $break=".", $pad="...") {/*{{{*/
        // return with no change if string is shorter than $limit   
        if(strlen($string) <= $limit)  
            return $string;   
        // is $break present between $limit and the end of the string?   
        if(false !== ($breakpoint = strpos($string, $break, $limit))) {  
            if($breakpoint < strlen($string) - 1) {   
                $string = substr($string, 0, $breakpoint) . $pad;  
            }  
        }  
        return $string;  
    }/*}}}*/

    /**
     * @method-name : createZip().
     * @description : create a compressed zip file.
     *                $files=array('file1.jpg', 'file2.jpg', 'file3.gif');  
     *                create_zip($files, 'myzipfile.zip', true);
     * @parameter   : (array)$files.
     * @parameter   : (string)$destination.
     * @parameter   : (bool)$overwrite.
     * @return      : bool.
     * @author      : stephen.mo <stephen.mo@hotmail.com>
     * @date        : Mar 31,2011
     */
    static public function createZip($files = array(),$destination = '',$overwrite = false) {/*{{{*/
        //if the zip file already exists and overwrite is false, return false  
        if(file_exists($destination) && !$overwrite) { return false; }   
        //vars $valid_files = array();   
        //if files were passed in...   
        if(is_array($files)) {   
            //cycle through each file  
            foreach($files as $file) {  
                //make sure the file exists  
                if(file_exists($file)) {   
                    $valid_files[] = $file;  
                }   
            }   
        }

        //if we have good files...   
        if(count($valid_files)) {  
            //create the archive   
            $zip = new ZipArchive();   
            if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) { 
                return false;  
            }

            //add the files   
            foreach($valid_files as $file) {   
                $zip->addFile($file,$file);  
            }   
            
            //debug //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;   
            //close the zip -- done!  
            $zip->close();   
            //check to make sure the file exists  
            return file_exists($destination);  
        }   
        else {  
            return false;   
        }

    }/*}}}*/  

    /**
     * @method-name : unzipFile().
     * @description : unzip a file to destination directory.
     * @parameter   : (string)$file - path to zip file
     * @parameter   : (string)$destination - destination directory for unzipped files.
     * @return      : NULL
     * @author      : stephen.mo <stephen.mo@hotmail.com>
     * @date        : Mar 31,2011
     */
    static public function unzipFile($file, $destination) {/*{{{*/ 
        // create object  
        $zip = new ZipArchive() ;  
        
        // open archive  
        if ($zip->open($file) !== TRUE) {  
            die ('Could not open archive');
        }  
        
        // extract contents to destination directory  
        $zip->extractTo($destination);  
        
        // close archive  
        $zip->close();  
        echo 'Archive extracted to directory';  

    }/*}}}*/


    /**
     * @method-name : generatePasswordForm().
     * @description : generate a password form.
     * @parameter   : (int)$length - the length of form.
     * @parameter   : (int)$width - the width of form
     * @parameter   : (bool)$randomText - using random text.
     * @parameter   : (bool)$randNum - Is or not use random number or number len is $randomNum when $randomNum not equal 
     * zero.
     * @parameter   : (bool)$outType - out put type default array. else output text table.
     * @return      : mixed.
     * @author      : stephen.mo <stephen.mo@hotmail.com>
     * @date        : Mar 31,2011
     */
    static public function generatePasswordForm($length,$width,$randomText=true,$randomNum=0,$outTypeArray=true) {/*{{{*/
        $sourceText = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
        $sourceNum  = array(1,2,3,4,5,6,7,8,9,0);
        if ($length <= 0) return NULL;
        if ($width <=0 ) return NULL;
        $length = ($length > count($sourceText)) ? count($sourceText) : $length;
        $width  = ($width > count($sourceNum)) ? count($sourceNum) : $width;

        $output = array();
        $minLen = 1;
        $maxLen = ($randomNum > 4) ? 4 : $randomNum;
        
        //generate items for form.
        for($i=0;$i<$length;$i++) {/*{{{*/
            if (!$randomText) {
                $iTXT = $sourceText[$i];
            }
            else {
                $iTXT = $sourceText[rand() % count($sourceText)];
            }
            if (isset($output[$iTXT])) {
                $i--;
            }
            $output[$iTXT] = array();
        }/*}}}*/

        //generate random num. 
        foreach($output as $key=>$val) {/*{{{*/
            for ($j=0;$j<$width;$j++) {
                $rand = NULL;
                if ($randomNum <= 0) {
                    $minLen = rand(1,4);
                    $maxLen = rand($minLen,4);
                }
                for($m=$minLen;$m<=$maxLen;$m++) {
                    $sTXT = rand() % (count($sourceNum)-1);
                    $rand .= (empty($sTXT)) ? '0' : $sourceNum[$sTXT];
                }
                $output[$key][$j] = $rand;
            }
        }/*}}}*/
        
        //out put the form .
        if ($outTypeArray) return $output;

        //if need to output a form.
        /*{{{*/
        $lStr = "\t";
        for($c=0;$c<$width;$c++) {
            $lStr .= $sourceNum[$c]."\t";
        }
        $lStr .= "\n";
        print $lStr;
        
        $mstr = NULL; 
        foreach($output as $key=>$val) {
            $mstr .= "$key\t";
            foreach($val as $num=>$cdata) {
                $mstr .= "$cdata\t";
            }
            $mstr .= "\n";
        }
        print $mstr;
        /*}}}*/

    }/*}}}*/

    
    /**
     * @method-name : generateCaptcha().
     * @description : generate a string of captcha.
     * @parameter   : NULL
     * @return      : array 
     * @author      : stephen.mo <stephen.mo@hotmail.com>
     * @date        : Apr 1,2011
     */
    static public function generateCaptcha($lText=NULL) {/*{{{*/
        //load based-captcha class file. 
        require_once "BasedCaptcha.class.php";
        require_once "BasedConfig.class.php";

        //get config setting of image pic.
        $config = BasedConfig::$captcha_config; 
        $image  = new BasedCaptcha();

        $image->width  = $config['width'];
        $image->height = $config['height'];
        $image->backgroundPoint = $config['backgroundPoint'];
        $image->line = $config['line'];

        $image->Xamplitude = round(5 / 100 * $config['twist']);
        $image->Yamplitude = round(12 / 100 * $config['twist']);

        $colorRandom = rand(0,1);
        if (!empty($lText)) {
            $colorRandom = rand(1,2);      
        }
   
        $image->fonts = BasedConfig::$captcha_fonts[$colorRandom]; 
        $images['out'] = base64_encode($image->OutImage($lText));
        $images['txt'] = $image->getText();
        $images['name'] = $config['cookie_name'];     
        return $images;

    }/*}}}*/
    
    
     /**
     * @method-name : getCaptchaFromCard().
     * @description : generate a captcha string from card
     * @parameter   : (string)$data - source data.
     * @parameter   : (int)$long - the long card string.
     * @parameter   : (array)$bg_color - the background color sets.
     * @return      : array.
     * @author      : stephen.mo <stephen.mo@hotmail.com>
     * @date        : Apr 14,2011
     */   
    static public function getCaptchaFromCard($data,$long=6,$bg_color=array(255,255,255)) {/*{{{*/
        if (empty($data)) return FALSE;
        $source_data = json_decode($data,true);
        $currentTxt  = array_keys($source_data); 
        $txtTotal    = count($currentTxt);
        foreach($source_data as $key=>$val) {
            $sNum = count($val);
            $currentNum = ($sNum >= 9) ? 9 : $sNum;
            break;
        }

        //create random txt
        $strs   = array();
        $locals = array();
        $data   = array();
        $n = 0;
        for ($i=1;$i<=$long;$i++) {
            if ($i % 2 != 0) {
                $_txt = $currentTxt[rand(0,$txtTotal-1)]; 
                $locals[$n]['X'] = $_txt;
                $strs[] = $_txt;
            }
            else {
                $_num = rand(0,$currentNum);
                $locals[$n]['Y'] = $_num;
                $strs[] = $_num;
                $n++;
            }
        }
        
    
        foreach($locals as $val) {
            $x = $val['X'];
            $y = $val['Y'];
            $rev[] = $source_data[$x][$y];
        }
        $data['code'] = implode('',$rev);
        $data['captcha'] = implode('',$strs);
        return $data; 
        /*{{{*
        session_start ();
        header ( 'Content-type: image/png' );

        //创建图片
        $im = imagecreate($x=130,$y=45 );

        //第一次对 imagecolorallocate() 的调用会给基于调色板的图像填充背景色
        $bg = imagecolorallocate($im,255,255,255);//rand(0,200),rand(0,155),rand(0,155)); 


        $fontColor = imageColorAllocate ( $im, 255, 0, 0 );   //字体颜色
        $fontstyle = 'msyh.ttf';                   

        //产生随机字符
        $str_test = array('B','4','G','5');
        for($i = 0; $i < 4; $i ++) {
            $randAsciiNumArray = array(rand(48,57),rand(65,90));
            $randAsciiNum = $randAsciiNumArray[rand (0, 1 )];
            //$randStr = chr ($randAsciiNum);
            $randStr = $str_test[$i];
            imagettftext($im,30,rand(0,20)-rand(0,25),5+$i*30,rand(30,35),$fontColor,$fontstyle,$randStr);
            $authcode .= $randStr; 
        }




        $_SESSION['authcode'] = $randFourStr;//用户和用户输入的验证码做比较
        //干扰线
        for ($i=0;$i<8;$i++) {
            $lineColor = imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));
            imageline ($im,rand(0,$x),0,rand(0,$x),$y,$lineColor);
        }

        //干扰点
        for ($i=0;$i<250;$i++){
            imagesetpixel($im,rand(0,$x),rand(0,$y),$fontColor);
        }
        imagepng($im);
        imagedestroy($im);
        /*}}}*/

    }/*}}}*/
    
    
    
    
    
    
    /**
     * @method-name :
     * @description :
     * @parameter   :
     * @return      :
     * @author      : stephen.mo <stephen.mo@hotmail.com>
     * @date        : Mar 31,2011
     */

        

}

?>
